#include <stdio.h>
#include <fcntl.h>  /* File Control Definitions          */
#include <termios.h>/* POSIX Terminal Control Definitions*/
#include <unistd.h> /* UNIX Standard Definitions         */
#include <errno.h>  /* ERROR Number Definitions          */
#include<iostream>
using namespace std;

class serial_port
{
public:
  serial_port()
  {
    fd = open("/dev/ttyUSB0",O_RDWR | O_NOCTTY);//打开串口
    if(fd == -1)
    {
     printf("\n  Error! in Opening ttyUSB0.\n\n");
    }
    else
    {
     printf("\n  ttyUSB0 Opened Successfully.\n\n");
   
    tcgetattr(fd, &SerialPortSettings);
    //设置参数
    cfsetispeed(&SerialPortSettings,B115200);//设置波特率
    cfsetospeed(&SerialPortSettings,B115200);

    SerialPortSettings.c_cflag &= ~PARENB; //无奇偶校验码
    SerialPortSettings.c_cflag &= ~CSTOPB; //停止位为1
    SerialPortSettings.c_cflag &= ~CSIZE; /* Clears the Mask       */
    SerialPortSettings.c_cflag |=  CS8;   /* Set the data bits = 8 */

    SerialPortSettings.c_cflag &= ~CRTSCTS;//Turn off hardware based flow control (RTS/CTS)
    SerialPortSettings.c_cflag |= CREAD | CLOCAL;
    //Turn on the receiver of the serial port (CREAD),otherwise reading from the serial port will not work.
  
    SerialPortSettings.c_iflag &= ~(IXON | IXOFF | IXANY);//Turn off software based flow control (XON/XOFF).
    SerialPortSettings.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG);//Setting the mode of operation,etc NON Cannonical mode is recommended.
    SerialPortSettings.c_oflag &= ~OPOST;/*No Output Processing*/

    tcsetattr(fd, TCSANOW,&SerialPortSettings); 
    }
  }

 int getfd()
 {
   return fd;
 }

 ~serial_port()
 {
  close(fd);
 }

 void write_se(char [],int);
 void read_se(int);

private:
  int fd;
  struct termios SerialPortSettings;//定义接口  
};

void serial_port::write_se(char data[],int da_size)//写入数据
{
  int  bytes_written  =  0 ;                       
  bytes_written = write(fd,data,da_size);

  cout<<"  "<<data<<" is written to ttyUSB0.\n  "<<bytes_written<<" Bytes written to ttyUSB0.\n"<<endl;
}

void serial_port::read_se(int da_size)//读取数据
{  
  char read_buffer[da_size];
	int  bytes_read = 0;    /* Number of bytes read by the read() system call */
 	int i = 0;

  bytes_read = read(fd,read_buffer,da_size);/* Read the data  */

  cout<<"  "<<bytes_read<<" Bytes have been read."<<endl;
	for(i=0;i<bytes_read;i++)	 /*printing only the received characters*/
    {
      cout<<"  "<<read_buffer[i]<<endl;
    }
}

int main()
{
 char data[]={'1','2','3','4','5','6','7','8','9','\0'};//发送的数据
 int da_size=sizeof(data);//发送数据的长度
 serial_port serial;
 //初始化，设置串口信息
 if(serial.getfd()==-1)
 {
   return -1;
 }

 serial.write_se(data,da_size);
 serial.read_se(da_size);

 return 0;
}


